<!--
 * @Author: your name
 * @Date: 2021-04-12 13:00:43
 * @LastEditTime: 2022-03-04 16:08:34
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \cang-chu-guan-li-xi-tong\src\views\tuiKuGuanLi\saleOutCancelApple.vue
-->
<template>
  <a-card>
    <p style="font-size: 18px; text-align: center">其他出库退库</p>
    <br />
    <!-- 顶部的信息  -->
    <a-form-model ref="ruleForm" :model="Form" v-bind="layout" :rules="rules">
      <a-row>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据号" prop="document" ref="document">
            <a-input
              style="border: 0"
              v-model="Form.document"
              disabled
            ></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="单据日期"
            prop="document_date"
            ref="document_date"
          >
            <a-date-picker
              v-model="Form.document_date"
              type="date"
              placeholder="请选择时间"
              style="width: 100%"
              @change="
                (a, b) => {
                  this.Form.a = a;
                  this.Form.document_date = b;
                  this.Form.balance = b;
                }
              "
            />
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="仓库名称"
            prop="depotId_dictText"
            ref="depotId_dictText"
          >
            <a-select
              v-model="Form.depotId_dictText"
              showSearch
              style="width: 100%"
              @change="formDepotNameSelectChange"
            >
              <!-- @change="
                  (val) => {
                    const arr = val.split('|');
                    this.form.depotId_dictText = arr[2];
                    this.form.depotId = arr[0];
                  }
                " -->
              <a-select-option
                v-for="item in storageList"
                :key="item.depotId"
                :value="
                  item.depotId + '|' + item.depotNo + '|' + item.depotName
                "
                >{{ item.depotNo }} {{ item.depotName }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="申请部门"
            prop="deptId_dictText"
            ref="deptId_dictText"
          >
            <a-tree-select
              v-model="Form.deptId_dictText"
              show-search
              style="width: 100%"
              :tree-data="depTree"
              allow-clear
              @change="changeTreeNode"
            ></a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="客户">
            <a-select
              showSearch
              v-model="Form.clientId_dictText"
              @change="getsupplierId"
              @search="getAllsupplierList"
            >
              <a-select-option
                v-for="item in customerlist"
                :key="item.id"
                :value="item.No + '|' + item.name + '|' + item.id"
              >
                {{ item.No }} {{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="农户">
            <a-select
              v-model="Form.farmerId_dictText"
              @change="getfarmerId"
              @search="getAllfarmerList"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in farmerList"
                :key="item.id"
                :value="item.No + '|' + item.name + '|' + item.id"
              >
                {{ item.No }} {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="库存组织"
            prop="pkCalbody_dictText"
            ref="pkCalbody_dictText"
          >
            <a-select
              v-model="Form.pkCalbody_dictText"
              @change="getpk_calbodyId"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in InventoryOrganizationList"
                :key="item.id"
                :value="item.pkCalbody + '|' + item.bodyname"
              >
                {{ item.bodyname }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="收发类别"
            prop="sendReceiveType_dictText"
            ref="sendReceiveType_dictText"
          >
            <a-select
              placeholder=""
              v-model="Form.sendReceiveType_dictText"
              @change="shoufaleibieMethod"
            >
              <a-select-option
                v-for="(item, index) in shoufaleibieList"
                :key="index"
                :value="item.id + '|' + item.name"
                >{{ item.name }}
              </a-select-option>
            </a-select>
            <!-- <a-input v-model="Form.sendReceiveType_dictText" disabled>
            </a-input> -->
            <!-- <a-input v-model="Form.sendReceiveType_dictText" disabled>
            </a-input> -->
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="公司"
            prop="pkCorp_dictText"
            ref="pkCorp_dictText"
          >
            <a-tree-select
              v-model="Form.pkCorp_dictText"
              show-search
              style="width: 100%"
              allow-clear
              :tree-data="pk_corpList"
              @change="getpk_corpId"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="库管员">
            <a-select
              @change="getcwhsmanagerId"
              v-model="Form.cwhsmanagerid_dictText"
              showSearch
              style="width: 100%"
              @search="searchUserInfoList"
            >
              <a-select-option
                v-for="item in UserList"
                :key="item.userId"
                :value="item.workNo + '|' + item.userName + '|' + item.userId"
              >
                {{ item.workNo }} {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="业务员">
            <a-select
              @change="getsalesman"
              v-model="Form.cbizid_dictText"
              showSearch
              style="width: 100%"
              @search="searchUserInfoList"
            >
              <a-select-option
                v-for="item in UserList"
                :key="item.userId"
                :value="item.workNo + '|' + item.userName + '|' + item.userId"
              >
                {{ item.workNo }} {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="入库仓库">
            <a-select
              v-model="Form.cotherwhName"
              showSearch
              style="width: 100%"
              @change="RuKuCangKuMethod"
            >
              <a-select-option
                v-for="item in InstorageList"
                :key="item.depotId"
                :value="
                  item.depotNo + '|' + item.depotName + '|' + item.depotId
                "
                >{{ item.depotNo }} {{ item.depotName }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="备注">
            <a-input v-model="Form.remark"> </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>

      <!-- 根据源单生成  -->

      <!-- 生成原单按钮组件 -->
      <otherOutCancelApplyOrigin
        v-if="!updateTag"
        @select-data="setGoodsListInfoByOrigin"
      ></otherOutCancelApplyOrigin>

      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="dataSource"
        style="margin-top: 10px"
        :scroll="{ x: 2000 }"
        :pagination="false"
      >
        <!-- 仓库名称 -->
        <span slot="depotId" slot-scope="text, record">
          <a-input-number v-model="record.depotId" />
        </span>
        <!-- 存货名称 -->
        <span slot="invname" slot-scope="text, record">
          <a-select
            v-model="record.invname"
            style="width: 100%"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            @search="handleSearch"
            @change="getInventoryInfo(record)"
            showSearch
          >
            <a-select-option
              v-for="(item, index) in goodsList"
              :key="index"
              :value="
                item.inventoryId +
                '|' +
                item.invcode +
                '|' +
                item.invname +
                '|' +
                item.invspec +
                '|' +
                item.measname
              "
            >
              {{ item.invcode }} {{ item.invname }}{{ item.invspec }}
            </a-select-option>
          </a-select>
        </span>
        <!-- 数量 -->
        <span slot="quantity" slot-scope="text, record">
          <a-input-number v-model="record.quantity" :step="0.001" />
        </span>
        <!-- 出菇领料金额 -->
        <span slot="amountOfFruitPicking" slot-scope="text, record">
          <a-input v-model="record.amountOfFruitPicking" />
        </span>
        <!-- 备注 -->
        <span slot="remark" slot-scope="text, record">
          <a-input v-model="record.remark" />
        </span>

        <template slot="action" slot-scope="text, record">
          <span>
            <a @click="getGoodsShelves(record.key)">选择货架</a>
          </span>
          <span> </span>
        </template>

        <!-- <template slot="action" slot-scope="text, record">
          
          <span v-if="record.isNew">
            <a @click="cancle(record.key)">取消</a>
          </span>
        </template> -->
      </a-table>
      <a-button
        style="width: 100%; margin-top: 16px; margin-bottom: 8px"
        type="dashed"
        icon="plus"
        @click="newMember"
        >添加</a-button
      >

      <a-row style="margin-top: 20px">
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="审核人" ref="inspector" prop="inspector">
            <a-select
              v-model="Form.inspector"
              showSearch
              @change="getInspectorId"
              style="width: 100%"
            >
              <a-select-option
                v-for="item in inspectorList"
                :key="item.userId"
                :value="item.userId + '|' + item.workNo + '|' + item.userName"
              >
                {{ item.workNo }} {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="审核日期">
            <a-date-picker
              v-model="Form.balance"
              type="date"
              style="width: 100%"
              disabled
            />
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="制单人">
            <a-input disabled v-model="Form.singleProducerName"> </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row>
        <center>
          <a-button
            @click="submit"
            style="margin-right: 20px"
            :disabled="isAntiAudit"
          >
            保存
          </a-button>
          <a-button
            style="margin-right: 20px"
            :disabled="!isAntiAudit"
            @click="Auditfunction"
          >
            审核
          </a-button>
        </center>
      </a-row>
    </a-form-model>
    <GoodsShelvesInfo
      :goodsShelvesTag="goodsShelvesTag"
      :tableKey="tableKey"
      :storageId="storageId"
      ref="goodShelvesInfo"
      @get-goodShelveInfo="getGoodShelveInfo"
    ></GoodsShelvesInfo>
  </a-card>
</template>
<script>
import GoodsShelvesInfo from "../../components/common/GoodsShelvesInfo"; //

import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口
import moment from "moment";

import otherOutCancelApplyOrigin from "./otherOutCancelOrigin.vue"; //

// 规则
const rules = {
  document: [
    {
      required: true,
      message: "单据号不能为空！",
      trigger: "change",
    },
  ],

  depotId_dictText: [
    {
      required: true,
      message: "仓库名称不能为空！",
      trigger: "change",
    },
  ],

  deptId_dictText: [
    {
      required: true,
      message: "申请部门不能为空！",
      trigger: "change",
    },
  ],

  // warehouseName: [
  //   {
  //     required: true,
  //     message: "所属仓库不能为空！",
  //     trigger: "change",
  //   },
  // ],
  client: [
    {
      required: true,
      message: "客户不能为空",
      trigger: "change",
    },
  ],
  sendReceiveType_dictText: [
    {
      required: true,
      message: "收发类别不能为空！",
      trigger: "change",
    },
  ],

  inspector: [
    {
      required: true,
      message: "审核人不能为空！",
      trigger: "change",
    },
  ],
  // 仓位
  /*  position: [
    {
      required: true,
      message: "仓位不能为空！",
      trigger: "change",
    },
  ], */

  // 库管员
  cwhsmanager: [
    {
      required: true,
      message: "库管员不能为空！",
      trigger: "change",
    },
  ],

  // 业务流程
  cbiztype: [
    {
      required: true,
      message: "业务类型不能为空！",
      trigger: "change",
    },
  ],
  // 库存组织
  pkCalbody_dictText: [
    {
      required: true,
      message: "库存组织不能为空！",
      trigger: "change",
    },
  ],
  // 公司
  pkCorp_dictText: [
    {
      required: true,
      message: "公司不能为空！",
      trigger: "change",
    },
  ],
  document_date: [
    {
      required: true,
      message: "单据日期不能为空！",
      trigger: "change",
    },
  ],
};

// 列表
const columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
  },
  // {
  //   title: "仓位",
  //   dataIndex: "position",
  //   key: "position",
  //   align: "center",
  // },
  {
    title: "存货名称",
    dataIndex: "invname",
    key: "invname",
    align: "center",
    width: 300,
    scopedSlots: { customRender: "invname" },
  },
  {
    title: "存货编码",
    dataIndex: "invcode",
    key: "invcode",
    align: "center",
  },
  {
    title: "规格型号",
    dataIndex: "invspec",
    key: "invspec",
    align: "center",
  },
  {
    title: "单位",
    dataIndex: "measname",
    key: "measname",
    align: "center",
  },
  {
    title: "辅助单位",
    key: "auxiliaryUnit",
    dataIndex: "auxiliaryUnit",
    align: "center",
    width: 150,
    // scopedSlots: { customRender: "auxiliaryUnit" },
  },
  {
    title: "数量",
    key: "quantity",
    dataIndex: "quantity",
    align: "center",
    scopedSlots: { customRender: "quantity" },
  },
  {
    title: "单价",
    key: "unitPrice",
    dataIndex: "unitPrice",
    align: "center",
    // scopedSlots: { customRender: "unitPrice" },
  },
  {
    title: "金额",
    key: "money",
    dataIndex: "money",
    align: "center",
    // scopedSlots: { customRender: "money" },
  },
  {
    title: "出菇领料金额",
    key: "amountOfFruitPicking",
    dataIndex: "amountOfFruitPicking",
    align: "center",
    scopedSlots: { customRender: "amountOfFruitPicking" },
  },
  {
    title: "源单单号",
    key: "sourceNumber",
    dataIndex: "sourceNumber",
    align: "center",
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    align: "center",
    scopedSlots: { customRender: "remark" },
  },
  {
    title: "货架",
    dataIndex: "goodsShelves",
    key: "goodsShelves",
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    align: "center",
    fixed: "right",
    scopedSlots: { customRender: "action" },
  },
];

export default {
  components: {
    otherOutCancelApplyOrigin,
    GoodsShelvesInfo,
  },
  data() {
    return {
      shoufaleibieList: [], //收发类别列表
      UserList: [], // 库管员列表
      customerlist: [], //客户列表
      farmerList: [], // 农户列表
      InventoryOrganizationList: [], // 库存组织列表
      InstorageList: [], //入库仓库
      pk_corpList: [], // 公司列表
      workNoList: [], // 判重使用
      goodsList: [],
      // 子组件传参
      goodsShelvesTag: false,
      tableKey: 0,
      storageId: "",
      empty_: true,
      isAntiAudit: false,

      Form: {
        sendReceiveType: "",
      },

      storageList: [], // 仓库列表
      depTree: [], // 部门列表
      clientList: [], // 客户
      SyncBusinessTypeVoList: [], // 业务流程列表
      warehouseOrganizationList: [], // 库存组织列表
      inspectorList: [], // 审核人
      inventoryList: [], // 存货列表
      Auxiliary_Unitlist: [], // 辅助单位

      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },

      rules,
      columns,
      dataSource: [],

      updateTag: false,
    };
  },

  watch: {
    $route: function (to) {
      if (to.path == "/otherOutCancel") {
        this.initInfoMount();
      }
    },
  },
  mounted() {
    this.judgeDocument(); //判断单据号是否为空
    this.shoufaleibieListmethod(); //收发类别列表
    this.getDeparmentTree(); //获取部门树
    this.getSyncInventoryOrganizationList(); //获取库存组织
    this.getpk_corpList(); //公司
    // this.getApplyOrder();
    this.getApplyStorage(); // 获取仓库
    this.getInStorage(); //入库仓库
    this.initInfoMount();
    this.getInspectorList(); // 仓库审核人员
  },
  methods: {
    // ————判断单据号是否为空————
    judgeDocument() {
      setTimeout(() => {
        if (this.Form.document === "") {
          this.$message.error("未获取到单据号,请刷新页面重试");
        }
      }, 3000);
    },

    async handleSearch(value) {
      var goodsList_invname = [];
      var goodsList_invspec = [];
      if (value.match(/^[ ]*$/)) {
        console.log("字符串为空或全空格");
      } else {
        this.goodsList = [];
        console.log("value", value);
        let query = "?name=" + value;
        console.log("query", query);
        if (value == "" || value == null) {
          this.goodsList = [];
        } else {
          await comHttp
            .getgetSearchInventoryInformationFile(query)
            .then((res) => {
              console.log("结果为", res);
              // this.goodsList = res.result;
              for (let i = 0; i < res.result.length; i++) {
                if (
                  res.result[i].invspec == "null" ||
                  res.result[i].invspec == null
                ) {
                  res.result[i].invspec = "";
                }
                if (
                  res.result[i].measname == "null" ||
                  res.result[i].measname == null
                ) {
                  res.result[i].measname = "";
                }
                let data = {
                  inventoryId: res.result[i].pkInvbasdoc, // 存货 id
                  invcode: res.result[i].invcode, //存货编码
                  invname: res.result[i].invname, //存货名称
                  invspec: res.result[i].invspec, //规格型号
                  measname: res.result[i].measname, //单位
                };
                goodsList_invname.push(data);
              }
            });
          let queryInventoryBySpec = "?invspec=" + value;
          //规格型号模糊查询
          await comHttp
            .getqueryInventoryBySpec(queryInventoryBySpec)
            .then((res) => {
              console.log("结果规格型号模糊查询", res);

              goodsList_invspec = res.result.list.map((item) => {
                return {
                  inventoryId: item.pkInvbasdoc,
                  invcode: item.invcode,
                  invname: item.invname,
                  invspec: item.invspec,
                  measname: item.measname,
                };
              });
            });
          //todo 合并去重函数
          await this.mergeArray(goodsList_invname, goodsList_invspec);
        }
      }
    },
    //todo 合并去重函数
    mergeArray(arr1, arr2) {
      let arrs = [...arr1, ...arr2];

      //根据inventoryId去重
      let map = new Map();
      for (let item of arrs) {
        if (!map.has(item.inventoryId)) {
          map.set(item.inventoryId, item);
        }
      }
      this.goodsList = [...map.values()];
    },
    // 获取存货信息
    async getInventoryInfo(record) {
      console.log("record11111111111111111111111111", record);
      let key = record.key;
      let target = this.dataSource.filter((item) => item.key === key)[0];
      console.log("target", target);
      // 分割字符串,取出来存货编码
      let array = target.invname.split("|");
      console.log("array", array);
      target.inventoryId = array[0];
      target.invcode = array[1]; // 赋值给存货编码
      target.invname = array[2]; // 赋值给存货名称

      if (array[3] != "null") {
        target.invspec = array[3]; // 赋值给规格型号
      } else {
        target.invspec = "";
      }

      if (array[4] != "null") {
        target.measname = array[4]; // 赋值给单位
      } else {
        target.measname = ""; // 赋值给单位
      }

      // console.log("目标物品信息:::::",target.goodsList)

      // 递归查询出来物品信息
      // let goodsInfomation = [];
      // for (let i = 0; i < this.goodsList.length; i++) {
      //   if (this.goodsList[i].inventoryNo == array[0]) {
      //     goodsInfomation = this.goodsList[i];
      //   }
      // }
      // console.log("物品信息::::", goodsInfomation);
      // target.standardModel = goodsInfomation.standardModel;
      // target.unit = goodsInfomation.unit;
      target.auxiliaryUnit = ""; // 重置辅助单位
      target.auxiliaryUnitId = ""; // 重置辅助单位
      target.giveawayId = 2; //

      // target.BatchList = await this.getBatchNumberList(
      //   target.depotId,
      //   goodsInfomation.inventoryId
      // ); // 获取批次列表
      /*  console.log(" target.position", target.position);
      if (target.position == undefined || target.position == "undefined") {
        target.BatchList = await this.getBatchNumberList(
          target.depotId,
          target.inventoryId
        );
      } else {
        target.BatchList = await this.getBatchNumberList(
          target.depotId,
          target.inventoryId,
          target.position
        );
      } */

      // console.log("批次号列表::::", target.BatchList);
      console.log("批次号列表::::", target.BatchList);
      //获取现存总数量
      // target.balance = await this.getBalanceTemp(
      //   // target.depotId, //仓库Id
      //   // target.inventoryId //存货 id
      //   record
      // );
    },
    //收发类别触发函数
    shoufaleibieMethod(value) {
      console.log("收发类别触发函数value", value);
      let array = value.split("|");
      console.log("array", array);
      // 表格自动填充所属单位
      this.Form.sendReceiveType = Number(array[0]); //收发类别id
      this.Form.sendReceiveType_dictText = array[1]; //收发类别name
      console.log("Form", this.Form);
    },
    //收发类别列表
    shoufaleibieListmethod(queryPath = "") {
      console.log("hfougdiuy");
      comHttp.getReceiveSendTypeListAll(queryPath).then((res) => {
        console.log("收发类别列表", res);
        this.shoufaleibieList = res.result;
      });
    },

    // 仓库名称
    formDepotNameSelectChange(value) {
      let array = value.split("|");
      console.log("仓库名称", value);
      this.Form.depotId = array[0];
      this.Form.depotId_dictText = array[2];
      // 获取物品信息列表,根据仓库编码
      // let goodsList = this.getGoodSInfo(array[0]);

      // 根据仓库查询物品信息,并存储到相应的物品信息表中
      for (let i = 0; i < this.dataSource.length; i++) {
        this.dataSource[i].depotId = array[0];
        this.dataSource[i].depotNo = array[1];
        this.dataSource[i].depotName = array[2];
        this.dataSource[i].batchNumber = this.todayBatchNumber;
        // ---                                      ---//
        // this.getGoodSInfo2(this.dataSource[i], array[0]);
        // this.getPositionListById(this.dataSource[i], array[0]); // 获取仓位信息
      }
      console.log("仓库获取:::::", this.dataSource);
    },

    getApplyStorage() {
      this.storageList = [];
      comHttp.getAllNumberName_new_forU8c().then((res) => {
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            depotId: res.result[i].pkStordoc,
          };
          this.storageList.push(data);
        }
      });
    },

    // 部门下拉框选择
    changeTreeNode(a) {
      console.log("a", a);
      let array = a.split("|");

      this.Form.deptId = array[0];
      this.Form.applicationDept = array[1];
      this.Form.deptId_dictText = array[1];
    },

    // 获取部门列表
    getDeparmentTree() {
      console.log("获取部门列表hanshu===");
      comHttp.getDepartmentList().then((res) => {
        if (res.success) {
          console.log("获取部门树", res);
          this.depTree = res.result;
          console.log(this.depTree, "111111111111111111");
          this.changeDeparmentData(this.depTree);
        }
      });
    },
    // 部门改变用友传递过来的数据为组件能识别的数据
    changeDeparmentData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.deptcode + " " + element.deptname;
        element["value"] = element.pkDeptdoc + "|" + element.deptname;
        element["children"] = element.syncDepartmentFilesEntityList;
        element["key"] = element.id;

        if (element.children) {
          this.changeDeparmentData(element.children);
        }
        // element["title"] = element.deptname;
        // element["children"] = element.syncDepartmentFilesEntityList;
        // element["key"] = element.pkDeptdoc;
        // element["value"] = element.pkDeptdoc;

        // if (element.children) {
        //   this.changeCorpData(element.children);
        // }
      });
    },

    //获取客户字典表
    getsupplierId(value, options) {
      console.log("供应商::::", value, options.key);
      let array = value.split("|");
      console.log("array", array);
      // this.form.supplier_dictText = array[1];
      // this.form.supplier = array[2];
      this.$set(this.Form, "clientId_dictText", array[1]);
      this.$set(this.Form, "clientId", array[2]);
    },
    // 客户模糊查询
    getAllsupplierList(value) {
      if (value != "") {
        comHttp
          .queryByLikeName("?customerName=" + value + "&custflag=0,2")
          .then((res) => {
            this.customerlist = [];
            console.log("所有的客户信息::::", res);
            for (let i = 0; i < res.result.list.length; i++) {
              let data = {
                No: res.result.list[i].custcode, //编号
                id: res.result.list[i].pkCumandoc,
                name: res.result.list[i].custname,
              };

              this.customerlist.push(data);
            }
          });
        console.log("this.customerlist", this.customerlist);
      }
    },
    // 农户列表
    getAllfarmerList(value) {
      if (value != "") {
        comHttp
          .queryByLikeName("?customerName=" + value + "&custflag=1,3")
          // .queryByLikeName("?customerName=" + value + "&custflag=0,2")
          .then((res) => {
            console.log("农户列表", res);
            this.farmerList = [];
            for (let i = 0; i < res.result.list.length; i++) {
              let data = {
                No: res.result.list[i].custcode, //编号
                id: res.result.list[i].pkCumandoc,
                name: res.result.list[i].custname,
              };
              this.farmerList.push(data);
            }
          });
      }
    },
    // 获取农户列表
    getfarmerId(value) {
      console.log("value::::", value);
      let array = value.split("|");
      this.Form.farmerId_dictText = array[1];
      this.Form.farmer = array[2];
      console.log("this.Form.farmer", this.Form.farmer);
    },

    // 获取库存组织列表
    getSyncInventoryOrganizationList() {
      comHttp.getSyncInventoryOrganizationList().then((res) => {
        console.log("库存组织", res);
        this.InventoryOrganizationList = res.result;
      });
    },
    // 获取库存组织Id
    getpk_calbodyId(value) {
      console.log("value", value);
      let array = value.split("|");
      this.Form.pkCalbody = array[0];
      console.log("this.Form.pkCalbody", this.Form.pkCalbody);
    },

    // 获取公司
    getpk_corpList() {
      comHttp.getpk_corpList().then((res) => {
        console.log("公司", res);
        this.pk_corpList = res.result;

        this.changeCorpData(this.pk_corpList);

        console.log(123124, this.pk_corpList);
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeCorpData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.unitcode + " " + element.unitname;
        element["value"] = element.pkCorp + "|" + element.unitname;
        element["children"] = element.syncCompanyEntityList;
        element["key"] = element.id;

        if (element.children) {
          this.changeCorpData(element.children);
        }
      });
    },
    // 获取公司Id
    getpk_corpId(value, label, extra) {
      console.log("11111111111111", value);
      console.log("2222222222", label);
      console.log("33333333333", extra);
      let array = value.split("|");
      this.Form.pkCorp = array[0];
      this.Form.pkCorpName = array[1];
    },

    // 获取入库仓库
    getInStorage() {
      this.InstorageList = [];
      // 获取仓库名称
      comHttp.getStorageName().then((res) => {
        // console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            depotName: res.result[i].storname, //仓库名称
            depotNo: res.result[i].storcode, //仓库编码
            depotId: res.result[i].pkStordoc, //id
          };
          this.InstorageList.push(data);
        }
        console.log("this.storageList", this.storageList);
      });
    },
    //入库仓库触发函数
    RuKuCangKuMethod(record) {
      let array = record.split("|");
      this.Form.cotherwhName = array[0];
      console.log("入库仓库record", record);

      this.Form.cotherwhName = array[1];
      this.Form.cotherwhid = array[2];
    },
    // 获取货架信息
    getGoodsShelves(key) {
      this.goodsShelvesTag = true;
      this.tableKey = key;
      this.storageId = "1001F3100000000002O0";

      setTimeout(() => {
        this.$refs.goodShelvesInfo.getGoodShelveInfo();
      }, 1000);
      //
    },

    // 关闭货架
    getGoodShelveInfo(key, goodsShelvesList) {
      let str = "";
      goodsShelvesList.forEach((element) => {
        str = str + element.inOutShelf + ",";
      });

      str = str.substring(0, str.length - 1);

      this.$set(this.dataSource[key - 1], "goodsShelves", str);

      this.goodsShelvesTag = false;
    },
    //————————————反审核开始————————————————————————————
    //! 反审核功能
    Auditfunction() {
      this.updateSubmit(); // 更新表单和物品数据
      // this.updateOrderAndGoodsData(); // 更新表单和物品数据

      // this.addGoodsData(); // 新增物品数据

      this.$message.success("审核成功");
      //标志位修改
      this.postSynchronized("未同步");
      this.update_audit("未反审核");
      // this.update_Mark(1);

      // 跳转回列表页面
      this.$router.push("/otherOutCancelList");
    },
    //! 是否同步标志位
    postSynchronized(isOrNo) {
      let data = {
        id: this.Form.id,
        isSynchronized: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
    //是否反审核标志位
    update_audit(isOrNo) {
      let data = {
        id: this.Form.id,
        isAntiAudit: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
    //审核标志位
    update_Mark(isOrNo) {
      let data = {
        id: this.form.id,
        auditMark: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
    //————————————反审核结束————————————————————————————
    /* ------------------------------- 其他,表头和表尾 ----------------------------- */
    // 申请单号
    getApplyOrder() {
      let queryPath = "?string=QTCKT-";
      comHttp.getOrder(queryPath).then((res) => {
        this.Form.document = res.message;
      });
    },
    // 审核人
    getInspectorList() {
      const roleName = "仓库审核人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.inspectorList.push(data);
        }
      });
    },
    // 获取审核人Id
    getInspectorId(value, options) {
      this.Form.inspectorId = options.key;
    },

    /* -------------------------- 表格 ------------------------- */

    // 通过源单生成数据
    setGoodsListInfoByOrigin(data) {
      console.log("传递过来的数据:::::", data);
      // 给表单赋值
      // 所属仓库
      this.Form.depotId_dictText = data.goodsList[0].depotId_dictText;
      this.Form.deptId = data.deptId;

      // 部门
      this.Form.deptId = data.deptId;
      this.Form.deptId_dictText = data.deptId_dictText;

      // 客户
      this.Form.clientId = data.clientId;
      this.Form.clientId_dictText = data.clientId_dictText;
      // 农户
      this.Form.farmerId = data.farmerId;
      this.Form.farmerId_dictText = data.farmerId_dictText;
      // 公司
      this.Form.pkCorp_dictText = data.pkCorp_dictText;
      this.Form.pkCorp = data.pkCorp;

      // 库管员
      this.Form.cwhsmanagerid_dictText = data.cwhsmanagerid_dictText;
      this.Form.cwhsmanagerid = data.cwhsmanagerid;
      // 业务员
      this.Form.cbizid_dictText = data.cbizid_dictText;
      this.Form.cbizid = data.cbizid;

      // 库存组织
      this.Form.pkCalbody = data.pkCalbody;
      this.Form.pkCalbody_dictText = data.pkCalbody_dictText;

      //入库仓库
      this.Form.cotherwhid = data.cotherwhid;
      this.Form.cotherwhName = data.cotherwhName;

      // 收发类别
      this.Form.sendReceiveType_dictText = data.sendReceiveType_dictText;
      this.Form.sendReceiveType = data.sendReceiveType;

      // 备注
      this.Form.remark = data.remark;

      this.dataSource = data.goodsList; // 给列表赋值

      this.dataSource.forEach((element) => {
        element.remark = "";
        element.sourceNumber = data.document; //!这是2021-5-6号刚改成这样的。
        element.getGoodsShelves = ""; //!这是2021-5-6号刚改成这样的。
      });
    },

    // 页面和路由跳转加载函数
    initInfoMount() {
      if (typeof this.$route.query.Id != "undefined") {
        console.log("--------- 更新视图 销售退库  ----------");
        this.routerJumpSetInitInfo(this.$route.query.Id);
      } else {
        this.initInfo();
      }
    },
    // 初始化加载信息
    initInfo() {
      this.updateTag = false;
      this.Form = {
        balance: moment().format("YYYY-MM-DD"),
        document: "", // 单据号
        document_date: moment().format("YYYY-MM-DD"),
        singleProducerName: this.$store.state.user.info.username, // 制单人名称
        singleProducerId: this.$store.state.user.info.id, // 制单人Id
        sendReceiveType: "", // 收发类别
      };
      this.dataSource = [];
      this.getApplyOrder();
    },

    // 路由跳转,设置初始化信息
    routerJumpSetInitInfo(id) {
      if (this.$route.query.isAntiAudit == "已反审核") {
        this.isAntiAudit = true;
      }
      this.updateTag = true;

      comHttp
        .getInOrOutStorageOrderAndGoodsInfoById("?id=" + id)
        .then((res) => {
          console.log(res);
          this.Form = {};
          this.dataSource = [];
          /* ------------- 设置表单信息 -------------- */
          this.Form.id = res.result.list[0].id;
          this.Form.document = res.result.list[0].document;
          this.$set(
            this.Form,
            "document_date",
            res.result.list[0].documentDate
          );
          this.Form.depotId_dictText = res.result.list[0].storname; // 仓库名称
          // 部门
          this.Form.deptId_dictText = res.result.list[0].deptId_dictText;
          // 所属仓库

          // 客户
          this.Form.clientId_dictText = res.result.list[0].clientId_dictText;
          // 业务类型
          this.Form.cbiztype_dictText = res.result.list[0].cbiztype_dictText;
          // 农户
          this.Form.farmerId_dictText = res.result.list[0].farmerId_dictText;
          // 库管员
          this.Form.cwhsmanagerid_dictText =
            res.result.list[0].cwhsmanagerid_dictText;
          //业务员
          this.Form.cbizid_dictText = res.result.list[0].cbizid_dictText;
          // 公司
          this.Form.pkCorp_dictText = res.result.list[0].pkCorp_dictText;
          // 库存组织
          this.Form.pkCalbody_dictText = res.result.list[0].pkCalbody_dictText;
          //入库仓库
          this.Form.cotherwhName = res.result.list[0].cotherwhName;
          //备注
          this.Form.remark = res.result.list[0].remark;
          // 收发类别
          this.Form.sendReceiveType_dictText =
            res.result.list[0].sendReceiveType_dictText;
          this.Form.sendReceiveType = res.result.list[0].sendReceiveType;

          // 审核人
          this.$set(this.Form, "inspectorId", res.result.list[0].inspector);
          this.$set(
            this.Form,
            "inspector",
            res.result.list[0].inspector_dictText
          );

          // 制单人
          this.Form.singleProducerName =
            res.result.list[0].singleProducer_dictText;

          let i = 0;
          res.result.list.forEach((element) => {
            let data = {
              id: element.twoId,
              key: i + 1,
              invname: element.invname,
              invcode: element.invcode,
              invspec: element.invspec,
              measname: element.measname,
              auxiliaryUnit: element.auxiliaryUnit_dictText,
              sourceNumber: element.sourceNumber,
              remark: element.remarks,
              quantity: element.quantity,
              amountOfFruitPicking: element.amountOfFruitPicking,
            };
            i = i + 1;
            this.dataSource.push(data);
          });
        });
    },

    // 新增提交
    addSubmit() {
      let array = [];
      console.log("array", this.dataSource);

      this.dataSource.forEach((element) => {
        let data = {
          objectInformationId: element.objectInformationId, //据源单生成的物品列表接口中
          inventoryId: element.inventoryId,
          // auxiliaryUnit: element.auxiliaryUnit,
          quantity: element.quantity,
          sourceNumber: element.sourceNumber,
          amountOfFruitPicking: element.amountOfFruitPicking,
          remark: element.remark,
          depotId: element.depotId, // 仓库名称
          // storageUnit：this.Form.所属仓库
        };
        array.push(data);
      });

      //  let  array
      let submitData = {
        balance: moment(this.Form.document_date).format("YYYY-MM-DD"),
        auditMark: 2, // 未审核是 1 , 已审核是 2
        bookkeepingMark: 2,
        inOutCategoryIdentification: 11, // 销售退库
        inOutIdentification: 3, // 退库
        pkCorp: this.Form.pkCorp, //公司Id
        // saleOrderAddId: this.Form.saleOrderAddId, // 销售订单Id
        document: this.Form.document, // 单据号
        cbiztype: this.Form.cbiztype, // 业务类型
        deptId: this.Form.deptId, // 部门
        clientId: this.Form.clientId, // 客户
        documentDate: moment(this.Form.document_date).format("YYYY-MM-DD"), // 单据日期
        pkCalbody: this.Form.pkCalbody, // 库存组织
        cotherwhid: this.Form.cotherwhid, // 入库仓库

        inspector: this.Form.inspectorId, // 审核人
        singleProducer: this.Form.singleProducerId, // 制单人
        sendReceiveType: this.Form.sendReceiveType, //? 收发类别，刚被告知要改成可修改

        warehouseObjectInformationEntities: array,
      };

      console.log("要提交的数据为:::::", submitData);
      if (this.dataSource.length != 0) {
        this.checkempty(submitData); //校验
        if (this.empty_ === true) {
          // 保存退库信息
          comHttp.addInOrOutStorageOrderAndGoods(submitData).then((res) => {
            if (res.success == true) {
              this.$message.success("保存成功");
              // this.saveGoodsShelvesInfo(res.result.list);
              this.initInfo();
              this.ResetAll();
            } else {
              this.$message.error("保存失败");
            }
          });
        }
      } else {
        this.$message.error("请添加列表信息!");
      }
    },
    //  校验是否为空
    checkempty(submitData) {
      this.empty_ = true;
      console.log("11111", submitData);
      var message = []; //提示信息
      /*  if (this._xxx.length === 0) {
        this.empty_ = false;
        message.push("请添加列表信息!" + "\xa0\xa0\xa0");
      } */
      /* if (this.DataSource.element.length ===0) {
        this.empty_ = false;
        message.push("请添加列表信息!" + "\xa0\xa0\xa0");
      } */
      this.dataSource.forEach((element) => {
        console.log("element", element);
        if (!element.depotId) {
          this.empty_ = false;
          message.push("请再选择一次仓库!" + "\xa0\xa0\xa0");
        }
        if (!element.invname) {
          this.empty_ = false;
          message.push("存货信息不能为空!" + "\xa0\xa0\xa0");
        }
        if (!element.quantity) {
          this.empty_ = false;
          message.push("存货数量不能为空!" + "\xa0\xa0\xa0");
        }
      });

      if (!this.empty_) {
        this.$message.error(message);
      }
    },
    // 修改提交
    updateSubmit() {
      let array = [];
      this.dataSource.forEach((element) => {
        let data = {
          id: element.id,
          quantity: element.quantity,
          remark: element.remark,
        };
        array.push(data);
      });

      let submitForm = {
        id: this.Form.id,
        inspector: this.Form.inspectorId,
        sendReceiveType: this.Form.sendReceiveType, //?刚加的

        documentDate: moment(this.Form.document_date).format("YYYY-MM-DD"),
        warehouseObjectInformationEntities: array,
      };

      // 修改全部的信息
      comHttp.updateInOrOutStorageOrderAndGoods(submitForm).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.$message.success("修改成功");
        } else {
          this.$message.error("修改失败");
        }
      });
    },
    // 提交
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          //  这是新增提交
          if (this.updateTag == false) {
            this.addSubmit();
          } else {
            // 这是修改提交
            this.updateSubmit();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 保存货架信息
    saveGoodsShelvesInfo(data) {
      let array = [];
      for (let i = 0; i < data.length; i++) {
        let submitData = {
          objectId: data[i].id,
          positionId: this.DataSource[i].position,
          inOutShelf: this.DataSource[i].goodsShelves.split(","),
          isOut: 1,
        };
        array.push(submitData);
      }
      console.log("提交数据", array);
      comHttp.saveShelfInfo(array).then((res) => {
        console.log("213", res);
      });
    },
    // 重置所有信息
    ResetAll() {
      this.Form = {
        id: "", // id
        document: "", // 单据号
        documentDate: moment().format("YYYY-MM-DD"), // 单据日期
        depotName: "", // 仓库名称
        depotNo: "", // 仓库编号
        depotId: "", // 仓库Id
        depotId_dictText: "",
        deptId_dictText: "",
        clientId_dictText: "",
        // storageUnit: "", // 所属单位名称
        // storageUnitId: "", // 所属单位Id
        storageUnitNo: "", // 所属单位编号
        department: "", // 部门名称
        deptId: "", // 部门id

        sendReceiveType: "", // 收发类别名称
        sendReceiveTypeId: "", // 收发类别Id
        projectsUnderConstruction: "", // 在建项目Id
        projectsUnderConstruction_text: "", // 在建项目name
        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
        balance: moment().format("YYYY-MM-DD"), // 审核日期
        remarks: "", //?备注
        singleProducer: this.$store.state.user.info.username, // 制单人名称
        singleProducerId: this.$store.state.user.info.id, // 制单人Id
      };
      this.dataSource = [];
      this.submitData = {
        document_date: moment().format("YYYY-MM-DD"), // 单据日期,
        storageUnit: "",
        document: "",

        cwhsmanager: "", // 库管员
        cwhsmanagerId: "", // 库管员Id

        singleProducer: this.$store.state.user.info.username, // 制单人名称
        singleProducerId: this.$store.state.user.info.id, // 制单人Id
        sendReceiveType: "", // 收发类别名称
        sendReceiveTypeId: "", // 收发类别Id
        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
        balance: moment().format("YYYY-MM-DD"), // 审核日期
      };
      this.getApplyOrder();
    },
    // 库管员列表
    getcwhsmanagerId(data) {
      let array = data.split("|");
      this.Form.cwhsmanagerid_dictText = array[1];
      this.Form.cwhsmanagerid = array[2];
      console.log(" this.Form", this.Form);
    },
    // 业务员列表
    getsalesman(data) {
      let array = data.split("|");
      this.Form.salesman = array[2];
      this.Form.cbizid_dictText = array[1];
      this.Form.cbizid = array[2];
      console.log("this.Form.cbizid ", this.Form.cbizid);
      console.log("this.Form.salesman ", this.Form.salesman);
    },
    // 查询人员信息列表
    searchUserInfoList(value) {
      // this.UserList = [];
      if (value != "") {
        let queryPath = "?username=" + value;
        comHttp.getUserInfoByUserName(queryPath).then((res) => {
          for (let i = 0; i < res.result.list.length; i++) {
            if (!this.workNoList.includes(res.result.list[i].workNo)) {
              let data = {
                userName: res.result.list[i].username,
                userId: res.result.list[i].id,
                workNo: res.result.list[i].workNo,
              };
              this.UserList.push(data);
              this.workNoList.push(res.result.list[i].workNo);
            }
          }
        });
      }
    },

    // 表格添加新的一条记录
    newMember() {
      console.log("增加一条记录");
      this.savebalance = Infinity;
      this.dataSource.push({
        key: this.dataSource.length + 1,
        isNew: true,

        depotNo: "", // 仓库编码、
        depotId: this.Form.depotId, //仓库id
        quantity: "", //数量
        unitPrice: "", //单价
        invcode: "", // 存货编码
        invname: "", //  存货名称

        // standardModel: "", //规格型号
        invspec: "", //规格型号
        measname: "", // 单位
        position: "", // 仓位
        sourceNumber: "", // 源单单号（外键）
        batchNumber: "", // 批次号
        giveaway: "2", // 是否赠品
        remark: "", // 备注
        goodsList: [], // 物品信息列

        deliveryDate: moment().format("YYYY-MM-DD"), //入库日期
      });
      console.log("this.dataSource", this.dataSource);
    },
  },
};
</script>
